/** ****************************************************************************
 * CopyRight (C) 2012 Sharadendu Sinha.
 * Licensing : FreeBSD 
 *
 * @(#) $Id$
 */
package com.sps.test.signalling;

import com.sps.signalling.Signal;
import com.sps.signalling.SignallingEntity;
// This is the signal emmiting entity
public class Timer extends SignallingEntity implements Runnable
{
	private final long diff;
	private Thread executionThread;
	private boolean stop = false;
	private int counter = 0;
	
	// name of the signal 
	public static final String SIGNAL_TIMER_TICK = "SIGNAL_TIMER_TICK";
	
	public Timer(long diff)
	{
		this.diff = diff;
		// create signal object 
		new Signal(SIGNAL_TIMER_TICK, this);
	}

	@Override
	public void run()
	{
		counter = 0;
		try
		{
			while(!stop)
			{
				Thread.sleep(diff);
				// emit signal 
				emit(SIGNAL_TIMER_TICK, counter++);
			}
		}
		catch(InterruptedException e)
		{
			e.printStackTrace();
		}
	}
	
	public void start()
	{
		this.stop = false;
		if(executionThread == null || !executionThread.isAlive())
		{
			executionThread = new Thread(this);
			executionThread.start();
		}
	}
	
	public void stop()
	{
		this.stop = true;
		if(executionThread != null && executionThread.isAlive())
		{
			try
			{
				executionThread.join();
			}
			catch(InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		executionThread = null;
	}
}
